<script setup>
import {onMounted, reactive, ref} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";
import {Plus} from "@element-plus/icons-vue";
import QuillEditor from "@/components/QuillEditor.vue";

//定义一个数据总条数

const formInline = reactive({
  articlename: '',
  pageNum:1,
  pageSize:3
})
const total=ref(0);
const isAdd = ref(true); // 标记是添加还是修改
const saveOrUpdateVisible = ref(false);
const saveOrUpdateTitle = ref('添加');
const fileList = ref([]);
const imageUrl=ref('');
const article=ref(
    {
      articlename: '',
      articleintroduce: '',
      consultId: '',
      tabularchart: '',
      details: '',
      readquantity: '',
      collects:'',
      typeId:'',
      createtime:'',
      typename:'',
      consultname:''
    }
)


// 修改onEdit函数
const onEdit = row => {
  saveOrUpdateTitle.value = '编辑';
  saveOrUpdateVisible.value = true;
  article.value = { ...row };
  selectedTypeName.value=article.value.articletype.name
  selectedConsultName.value=article.value.consult.name
  console.log('article',article.value)
  console.log('selectedTypeName',selectedTypeName.value)
  // 初始化图片列表
  const images = row.tabularchart?.split(',') || [];
  fileList.value = images.map(img => ({
    name: img,
    url: loacalUrl + img
  }));

  // 显示最后一张图片
  imageUrl.value = images.length > 0 ? loacalUrl + images[images.length - 1] : '';
  isAdd.value = false;
};

//去添加的页面
const onAdd = ()=>{
  saveOrUpdateTitle.value='添加'
  saveOrUpdateVisible.value=true
  selectedTypeName.value=''
  article.value={
    articlename: '',
    articleintroduce: '',
    consultId: '',
    tabularchart: '',
    details: '',
    readquantity: '',
    collects:'',
    typeId:'',
    createtime:'',
    typename:'',
    consultname:''
  }
  fileList.value=[]
  isAdd.value = true; // 设置为添加模式
}

// 取消
const closearticle = ()=>{
  saveOrUpdateVisible.value=false
  imageUrl.value=''
  fileList.value=[]
}

// 保存
//添加和修改
const savearticle = ()=>{
  const selectedType = typeList.value.find(type => type.name === selectedTypeName.value);
  if (!selectedType) {
    ElMessage.error('请选择文章类型');
    return;
  }
  article.value.typeId = selectedType.id; // 设置文章类型ID
  const selectedConsult = consultList.value.find(consult => consult.name === selectedConsultName.value);
  if (!selectedConsult) {
    ElMessage.error('请选择咨询师');
    return;
  }
  article.value.consultId = selectedConsult.id;

  if (saveOrUpdateTitle.value==='添加'){
    axios.post('addarticle',article.value)
        .then(res => {
          console.log('res', res);
          console.log('article',article.value)
          getArticleList()
          ElMessage({
            message: '添加成功！',
            type: 'success',
          })
        })
        .catch(err => {
          console.log('err', err)
        })
  }else if (saveOrUpdateTitle.value==='编辑'){
    axios.put('updatearticle', article.value)
        .then(res => {
          console.log('res', res);
          getArticleList()
          ElMessage({
            message: '修改成功！',
            type: 'success',
          })
        })
        .catch(err => {
          console.log(err)
        })
  }
  saveOrUpdateVisible.value=false
}




// 删除
const onDel = id=>{
  ElMessageBox.confirm(
      '真的要删除吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
            axios.delete('deletearticle',
                {
                  params: {
                    id: id
                  }
                })
                .then(res => {
                  console.log('res', res);
                  getArticleList()
                  ElMessage({
                    message: '删除成功！',
                    type: 'success',
                  })
                })
                .catch(err => {
                  console.log('err', err);
                  ElMessage({
                    message: '删除失败！',
                    type: 'error',
                  })
                })
          }
      )
}

const onSubmit = () => {
  getArticleList()
}


const tableData = ref()

// 分页
// 每页条数改变
const handleSizeChange = (val) => {
  formInline.pageSize=val
  formInline.pageNum=1
  getArticleList()
}
const handleCurrentChange = (val) => {
  formInline.pageNum=val
  getArticleList()
}

// 定义一个方法当页面加载后立即执行的代码
onMounted(()=>{
  console.log('页面加载了');
  getArticleList();
  getArticleType();
  getConsultList();
})

// 定义一个方法,用来动态调用后端接口,获取文章列表
const getArticleList=()=>{
  axios.get('article',
      {params:formInline
      })
      .then(res=>{
        console.log('res',res);
        total.value=res.data.data.total;
        tableData.value = res.data.data.list;
      })
      .catch(err=>{
        console.log('err',err);
      })
}
const typeList=ref()
const selectedTypeName=ref()
const getArticleType=()=>{
  axios.get('articletype')
      .then(res=>{
        console.log('res',res);
        typeList.value=res.data.data;
        console.log('typeList',typeList.value)
      })
      .catch(err=>{
        console.log('err',err);
      })
}

const consultList = ref()
const selectedConsultName=ref()
const getConsultList=()=>{
  axios.get('affconsult')
      .then(res=>{
        consultList.value=res.data.data;
        console.log('consultList',consultList.value)
      })
      .catch(err=>{
        console.log('err',err);
      })
}

const loacalUrl = 'http://localhost:8080/file/downLoad?fileName=';
//图片长传上传成功
const handleAvatarSuccess = (res, file) => {
  if(isAdd.value){
    //   添加模式,直接赋值
    article.value.tabularchart = res.data;
    imageUrl.value=URL.createObjectURL(file.raw);
  }else {
    //   修改模式,追加图片并更新最后一张
    const images = article.value.tabularchart ? article.value.tabularchart.split(",") : [];
    images.push(res.data);
    article.value.tabularchart = images.join(",");
    imageUrl.value=loacalUrl+res.data;
  }
};

// 修改文件移除处理
const handleRemove = (file, fileList) => {
  if (isAdd.value) {
    article.value.tabularchart = '';
    imageUrl.value = '';
  } else {
    // 过滤出剩余的图片并更新最后一张
    const remainFiles = fileList.map(f => f.response?.data || f.name);
    article.value.tabularchart = remainFiles.join(',');
    imageUrl.value = remainFiles.length > 0
        ? loacalUrl + remainFiles[remainFiles.pop()]
        : '';
  }
};
const detailsDialogVisible = ref(false); // 详情内容弹框的显示状态
const currentArticleDetails = ref(''); // 当前文章的详情内容
// 显示详情内容的函数
const showDetails = (row) => {
  currentArticleDetails.value = row.details;
  detailsDialogVisible.value = true;
};
//
// // 文件超出限制
// const handleExceed = () => {
//   ElMessage.warning('只能上传一张图片');
// };
</script>

<template>
  <div class="about">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="输入文章关键字">
        <el-input v-model="formInline.articlename" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>



    <div class="mb20">
      <el-button @click="onAdd" type="primary" icon="Plus" plain>新增</el-button>
      <el-button type="danger" icon="Delete" plain>删除</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="编号" width="150" />
      <el-table-column prop="articlename" label="文章名称" width="120" />
      <el-table-column prop="articleintroduce" label="文章简介" width="120" />
      <el-table-column prop="consult.name" label="作者名" width="120" />
      <el-table-column prop="tabularchart" label="图片" width="120" >
        <template #default="scope">
          <el-image
              v-if="scope.row.tabularchart"
              style="width: 100px; height: 100px"
              :src="loacalUrl + scope.row.tabularchart"
          />
        </template>
      </el-table-column>
      <el-table-column prop="details" label="详情内容" width="120">
        <template #default="scope">
          <el-button type="text" @click="showDetails(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="readquantity" label="阅读量" width="120" />
      <el-table-column prop="collects" label="收藏量" width="120" />
      <el-table-column prop="createtime" label="创建时间" width="120" />
      <el-table-column prop="articletype.name" label="类型名" width="120" />

      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="onEdit(scope.row)">修改</el-button>
          <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 10px"
                   v-model:current-page="formInline.pageNum"
                   v-model:page-size="formInline.pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[1, 3, 5, 10]"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
    />
  </div>


  <!-- 添加，编辑弹框 -->
  <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="500">
    <el-form :model="article">
      <el-form-item label="文章类型" :label-width="formLabelWidth">
        <el-select v-model="selectedTypeName" placeholder="Select" style="width: 240px">
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="咨询师" :label-width="formLabelWidth">
        <el-select v-model="selectedConsultName" placeholder="Select" style="width: 240px">
          <el-option
              v-for="item in consultList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章名" :label-width="formLabelWidth">
        <el-input v-model="article.articlename" autocomplete="off" />
      </el-form-item>

      <el-form-item label="文章简介" :label-width="formLabelWidth">
        <el-input v-model="article.articleintroduce" autocomplete="off" />
      </el-form-item>

      <el-form-item label="图片" :label-width="formLabelWidth">
        <el-upload
            v-model:file-list="fileList"
            class="avatar-uploader"
            list-type="picture-card"
            action="http://localhost:8080/file/upload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :limit="isAdd ? 1 : Infinity"
            :on-exceed="handleExceed"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>

      </el-form-item>

      <el-form-item label="详情内容" :label-width="formLabelWidth">
        <quill-editor v-model:value="article.details" />
<!--        <el-input v-model="article.details" autocomplete="off" />-->
      </el-form-item>

      <el-form-item label="阅读量" :label-width="formLabelWidth">
        <el-input v-model="article.readquantity" autocomplete="off" />
      </el-form-item>

      <el-form-item label="收藏量" :label-width="formLabelWidth">
        <el-input v-model="article.collects" autocomplete="off" />
      </el-form-item>
      <el-form-item label="创建时间" :label-width="formLabelWidth">
        <el-input v-model="article.createtime" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closearticle">取消</el-button>
        <el-button type="primary" @click="savearticle">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 详情内容弹框 -->
  <el-dialog v-model="detailsDialogVisible" width="800">
    <div v-html="currentArticleDetails"></div>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display:  none;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>